/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.kategori;

import com.x3.purchasing.common.ClassConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author kris
 */
public class KategoriDAOImpl implements KategoriDAO {

    public KategoriDAOImpl() {
        ClassConnection.getTransactionProxyFactoryBean().setTarget(this);
    }

    public void insert(Kategori kategori) throws Exception {
        String sql = "INSERT INTO kategori(nama) VALUES(?)";
        ClassConnection.getJdbc().update(sql, new Object[]{
                    kategori.getNama()
                });
    }

    public void update(Kategori kategori) throws Exception {
        String sql = "UPDATE kategori SET nama=? WHERE id=?";
        ClassConnection.getJdbc().update(sql, new Object[]{
                    kategori.getNama(),
                    kategori.getId()
                });
    }

    public void delete(int id) throws Exception {
        String sql = "DELETE FROM kategori WHERE id=?";
        ClassConnection.getJdbc().update(sql, new Object[]{id});
    }

    public Kategori get(int id) throws Exception {
        Kategori kategori = null;
        String sql = "SELECT id,nama FROM kategori WHERE id=?";
        kategori = (Kategori) ClassConnection.getJdbc().queryForObject(sql, new Object[]{id}, new RowMapper() {

            public Object mapRow(ResultSet rs, int i) throws SQLException {
                Kategori temp = new Kategori();
                temp.setId(rs.getInt(1));
                temp.setNama(rs.getString(2));
                return temp;
            }
        });
        return kategori;
    }

    public List<Kategori> gets() throws Exception {
        List<Kategori> data = new ArrayList<Kategori>();
        String sql = "SELECT * FROM kategori ORDER BY nama";
        List<Map> rows = ClassConnection.getJdbc().queryForList(sql);
        for (Map m : rows) {
            Kategori kategori = new Kategori();
            kategori.setId(Integer.valueOf(m.get("id").toString()));
            kategori.setNama(m.get("nama").toString());
            data.add(kategori);
        }
        return data;
    }
}
